﻿using Mes.原料管理;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Mes.车间机床.Model;

namespace Mes.车间机床
{
    public partial class UpdateWorkshopForm : Form
    {
        private string _id;
        public UpdateWorkshopForm(string id)
        {
            InitializeComponent();
            _id = id;
            InitializeDataGridView();
            LoadWorkShopData();
        }

        /// <summary>
        /// 初始化DataGridView列
        /// </summary>
        private void InitializeDataGridView()
        {
            // 清空现有列
            dataGridViewUpdate.Columns.Clear();
            
            // 只添加需要的三个列
            dataGridViewUpdate.Columns.Add("MachineToolCode", "设备编号");
            dataGridViewUpdate.Columns.Add("MachineToolName", "设备名称");
            dataGridViewUpdate.Columns.Add("MachineToolType", "设备类型");
            
            // 设置列宽，让列填满整个DataGridView
            int totalWidth = dataGridViewUpdate.Width;
            int columnWidth = totalWidth / 3; // 平均分配宽度
            
            dataGridViewUpdate.Columns["MachineToolCode"].Width = columnWidth;
            dataGridViewUpdate.Columns["MachineToolName"].Width = columnWidth;
            dataGridViewUpdate.Columns["MachineToolType"].Width = columnWidth;
            
            // 设置自动调整列宽
            dataGridViewUpdate.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            
            // 设置只读
            dataGridViewUpdate.ReadOnly = true;
            dataGridViewUpdate.AllowUserToAddRows = false;
            dataGridViewUpdate.AllowUserToDeleteRows = false;
        }
        private async void LoadWorkShopData()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    client.BaseAddress = new Uri("http://121.40.174.148:8056/");
                    HttpResponseMessage response = await client.GetAsync($"api/WorkShop/GetWorkshopValue?Id={_id}");

                    if (response.IsSuccessStatusCode)
                    {
                        string json = await response.Content.ReadAsStringAsync();
                        if (string.IsNullOrEmpty(json))
                        {
                            MessageBox.Show("API 返回的数据为空！");
                            return;
                        }
                        var apiResponse = JsonConvert.DeserializeObject<WorkshopRepositoryss>(json);
                        // 检查 material 是否为
                        if (apiResponse?.code != 200 || apiResponse.data == null || apiResponse.data.Count == 0)
                        {
                            MessageBox.Show("API 返回的数据无效！");
                            return;
                        }
                        var workshop = apiResponse.data[0];
                        textUpdateWorkshopCode.Text = workshop.workshopCode?.ToString() ?? "";
                        textUpdateWorkshopName.Text = workshop.workshopName?.ToString() ?? "";
                        comUpdateWorkshopLocation.Text = workshop.workshoplocation?.ToString() ?? "";
                        comUpdateStates.Text = workshop.state?.ToString() ?? "";
                        textUpdateWorkshopPhone.Text = workshop.phone?.ToString() ?? "";
                        textUpdateHeader.Text = workshop.workshopHead?.ToString() ?? "";
                        
                        // 加载该车间下的机床信息
                        await LoadMachineDataForWorkshop(_id);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 加载指定车间下的机床信息
        /// </summary>
        /// <param name="workshopId">车间ID</param>
        private async Task LoadMachineDataForWorkshop(string workshopId)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    
                    // 调用机床查询API，传入车间ID作为查询条件
                    string url = $"https://localhost:7084/api/Machine/GetMachinevalue?WorkshopId={workshopId}";
                    HttpResponseMessage response = await client.GetAsync(url);

                    if (response.IsSuccessStatusCode)
                    {
                        string json = await response.Content.ReadAsStringAsync();
                        if (!string.IsNullOrEmpty(json))
                        {
                            // 清空现有数据
                            dataGridViewUpdate.Rows.Clear();
                            
                            try
                            {
                                // 尝试解析JSON
                                var dynamicObj = JsonConvert.DeserializeObject<dynamic>(json);
                                
                                if (dynamicObj is Newtonsoft.Json.Linq.JArray)
                                {
                                    // 直接是数组格式
                                    var machines = JsonConvert.DeserializeObject<List<MachineModel>>(json);
                                    if (machines != null && machines.Count > 0)
                                    {
                                        // 添加所有机床数据到DataGridView
                                        foreach (var machine in machines)
                                        {
                                            dataGridViewUpdate.Rows.Add(
                                                machine.machineToolCode,
                                                machine.machineToolName,
                                                machine.machineToolType
                                            );
                                        }
                                    }
                                }
                                else if (dynamicObj is Newtonsoft.Json.Linq.JObject)
                                {
                                    // 是对象格式，检查data字段
                                    var jobject = dynamicObj as Newtonsoft.Json.Linq.JObject;
                                    
                                    if (jobject["data"] != null)
                                    {
                                        if (jobject["data"] is Newtonsoft.Json.Linq.JArray)
                                        {
                                            // data字段是数组
                                            var machines = jobject["data"].ToObject<List<MachineModel>>();
                                            if (machines != null && machines.Count > 0)
                                            {
                                                // 添加所有机床数据到DataGridView
                                                foreach (var machine in machines)
                                                {
                                                    dataGridViewUpdate.Rows.Add(
                                                        machine.machineToolCode,
                                                        machine.machineToolName,
                                                        machine.machineToolType
                                                    );
                                                }
                                            }
                                        }
                                        else if (jobject["data"] is Newtonsoft.Json.Linq.JObject)
                                        {
                                            // data字段是对象，尝试解析为MachineRepository
                                            var apiResponse = JsonConvert.DeserializeObject<MachineRepository>(json);
                                            if (apiResponse?.code == 200 && apiResponse.data?.datas != null && apiResponse.data.datas.Count > 0)
                                            {
                                                // 添加所有机床数据到DataGridView
                                                foreach (var machine in apiResponse.data.datas)
                                                {
                                                    dataGridViewUpdate.Rows.Add(
                                                        machine.machineToolCode,
                                                        machine.machineToolName,
                                                        machine.machineToolType
                                                    );
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // 没有data字段，可能直接返回机床数组
                                        var machines = JsonConvert.DeserializeObject<List<MachineModel>>(json);
                                        if (machines != null && machines.Count > 0)
                                        {
                                            // 添加所有机床数据到DataGridView
                                            foreach (var machine in machines)
                                            {
                                                dataGridViewUpdate.Rows.Add(
                                                    machine.machineToolCode,
                                                    machine.machineToolName,
                                                    machine.machineToolType
                                                );
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($"解析机床数据时出错: {ex.Message}");
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show($"获取机床数据失败：{response.StatusCode}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载机床数据失败：{ex.Message}");
            }
        }

        private async void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                // 收集机床信息
                List<MachineToolDto> machines = new List<MachineToolDto>();
                
                // 从DataGridView中获取机床数据
                foreach (DataGridViewRow row in dataGridViewUpdate.Rows)
                {
                    if (row.IsNewRow) continue;
                    
                    string machineToolCode = row.Cells["MachineToolCode"].Value?.ToString() ?? "";
                    string machineToolName = row.Cells["MachineToolName"].Value?.ToString() ?? "";
                    string machineToolType = row.Cells["MachineToolType"].Value?.ToString() ?? "";
                    
                    if (!string.IsNullOrEmpty(machineToolCode))
                    {
                        machines.Add(new MachineToolDto
                        {
                            MachineToolCode = machineToolCode,
                            MachineToolName = machineToolName,
                            MachineToolType = machineToolType
                        });
                    }
                }

                var workshop = new
                {
                    Id = _id,
                    WorkshopCode = textUpdateWorkshopCode.Text,
                    WorkshopName = textUpdateWorkshopName.Text,
                    Workshoplocation = comUpdateWorkshopLocation.Text,
                    WorkshopHead = textUpdateHeader.Text,
                    Phone = textUpdateWorkshopPhone.Text,
                    state = comUpdateStates.Text,
                    Machine = machines
                };

                string json = JsonConvert.SerializeObject(workshop);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    client.BaseAddress = new Uri("https://localhost:7084/");
                    HttpResponseMessage response = await client.PostAsync(
                        "api/WorkShop/UpdateWorkShop",
                        content);

                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("修改成功！");
                        this.DialogResult = DialogResult.OK; // 通知主窗体刷新数据
                        this.Close();
                    }
                    else
                    {
                        string error = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"修改失败：{response.StatusCode}\n{error}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}");
            }
        }
    }
}
